Ext.define('TS.view.inv.OtherOutBillEditor',{
	extend: 'Ext.panel.Panel',
	border: false,
	bodyPadding:0,
	layout:'anchor',
	alias: 'widget.otheroutbilleditor',
	title: '其它出库单-新增',
	bill:null,
	autoScroll:true,
	mixins: {
        observable: 'Ext.util.Observable'
    },
	constructor:function(config) {
		var me = this;
		this.initConfig(config);
		if(config.bill) {
			this.bill = config.bill;
		}
        this.addEvents(
        	{'cellSpecialkey':true}
        );
		me.self.superclass.constructor.call(this,config);
	},
	initComponent:function() {
		//初始化业务员列表
		var me=this;
		var store = Ext.create('TS.store.base.EmpStore');
		var invComp = Ext.ComponentQuery.query('accmenu combobox')[0];
		var invModel = invComp.findRecordByValue(invComp.getValue());
		var deptId = invModel.get('deptId');
		store.load({params:{deptId:deptId}});		
		var invstore=Ext.create('TS.store.base.InvAddsStore');
		invstore.load();
		var billTypeStore = Ext.create('Ext.data.Store',{
			fields:['key','value'],
			data : [
			   {key:-3,value:'其它出库单'}
			]
		});
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	    	clicksToEdit: 1,
	    	listeners:{
	    		'edit':function(editor, e) {
	    			//编辑数量或单价重新计算金额
	    			if(e.column.dataIndex == "quantity" || e.column.dataIndex == "price" || e.column.dataIndex=='settlePrice') {
	    				e.record.set('amount',e.record.get('quantity')*e.record.get('price'));
	    				//e.record.set('amount',e.record.get('quantity')*e.record.get('settlePrice'));
	    				e.grid.getView().refresh();
	    				//e.grid.fireEvent('cellkeydown')    				
	    			}
	    			if(e.column.dataIndex == "price" ) {
	    				e.record.set('settlePrice',e.record.get('price'));
	    				e.grid.getView().refresh(); 				
	    			}
	    		},
	    		'beforeedit':function(editor, e, eOpts ){
	    			var prod=null;
	    			if(e.record.product){
	    				if(e.column.dataIndex=='quantity')
	    					editor.decimalPrecision=e.record.product.get('qtyScale');
	    			}
	    		},
	    		scope:this
	    	}
	    });		
		this.items = [
       		    {
       		    	xtype:'form',
       		    	border: false,
					bodyPadding:0,
       		    	items:[{
    		    	xtype: 'fieldset',
    	            title: '基本信息',
    	            anchor:'100% 20%',
    	            
    	            minHeight:100,
                    defaults: {
                        anchor: '100%',
                        bodyPadding:0,
                        layout: {
                            type: 'hbox'
                        },
                        fieldDefaults:{
							//readOnly:true,  
							//labelAlign:'left',
							labelWidth:55
				    	}
                    },
                    items:[
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          {
    	          		    	    	xtype: 'triggerfield',
    	        		    	    	emptyText:'请输入客户编码或名称',
    	        		    	    	trigger1Cls:Ext.baseCSSPrefix + 'form-search-trigger',
    	        		    	    	onTriggerClick:function(e){e.keyCode=e.ENTER;this.fireEvent('specialkey',this,e);},
    	        		            	name: 'customerCode',
     	        		            	fieldLabel: '客户编码',
    	        		            	labelStyle:'text-align:right',
    	        		            	allowBlank:false
    	                	          },
    	                	          {
    	          		            	xtype: 'textfield',
    	        		            	readOnly:true,
    	        		            	width:374,
    	        		            	name: 'customerName',
    	        		            	labelStyle:'text-align:right',
    	        		            	fieldLabel: '客户名称',
    	        		            	allowBlank:false
    	                	          },
      	                	          {
      	                	        	  xtype:'datefield',
      	                	        	  name:'billDate',
      	                	        	  labelStyle:'text-align:right',
      	                	        	  fieldLabel:'单据日期',
      	                	        	  allowBlank:false,
      	                	        	  format:'Y-m-d'
      	                	          },
					                  {
										  xtype: 'hiddenfield',
					                      name : 'billId'
					                  }
    	                	   ]
    	                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          { 
    	                	        	xtype:'combobox',
    	          		        		fieldLabel: '部门',
    	                                labelStyle:'text-align:right',
    	                                name:'deptName',
    	        		        		allowBlank:false
    	                	          },
    	                	          {
    	                	        	  xtype:'textfield',
    	                	        	  fieldLabel:'单据编号',
    	                	        	  labelStyle:'text-align:right',
    	                	        	  name:'billCode',
    	                	        	  allowBlank:false
    	                	          },
    	                	          {
    	                	        	  xtype:'combobox',
    	                	        	  fieldLabel:'单据类型',
      	                                  labelStyle:'text-align:right',
      	                                  name:'billType',
    	                	        	  allowBlank:false,
    	                	        	  store:billTypeStore,
    	                	        	  displayField:'value',
    	                	        	  valueField:'key',
    	          						  forceSelection:true,
    	        						  typeAhead : true
    	                	          },
      	                	          {
	    	      		        		xtype:'textfield',
	    	    		        		readOnly:true,
	    	    		        		labelStyle:'text-align:right',
	    	    		        		fieldLabel:'制单人',
	    	    		        		name:'makerName',
	    	    		        		allowBlank:false
    	                	          }
    	                	   ]
    	                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          { 
      	                	        	xtype:'combobox',
      	          		        		fieldLabel: '业务员',
      	        		        		name:'empId',
      	        		        		store:store,
      	        		        		queryMode:'local',
    	                                labelStyle:'text-align:right',
    	                                allowBlank:false,
    	                                displayField:'empName',
    	                                valueField:'empId',
    	        						forceSelection:true,
    	        						typeAhead : true,
    	        						listeners:{
    	        							select:function(combo,records) {
    	        								var model = this.up('form').getRecord();
    	        								model.setemp(records[0]);
    	        							}
    	        						}
      	                	          },
    	                	          {
    	                	        	  xtype:'textfield',
    	                	        	  fieldLabel:'备注',
    	                	        	  width:374,
      	                                  labelStyle:'text-align:right',
    	                	        	  name:'remark'
    	                	          },
    	                	          {
    	                	        	  xtype:'textfield',
    	                	        	  fieldLabel:'单据名称',
      	                                  labelStyle:'text-align:right',
    	                	        	  name:'billName'
    	                	          }
    	                	   ]
    	                   }
    	            ]
    	          }]
    		    },
    		    {
    		    	xtype: 'form',
            		border: false,
					bodyPadding:0,   
                    items:[{
    		    	xtype: 'fieldset',
    	            title: '编辑明细',
    	            minHeight:100,
	                anchor:'100% 20%',                    
					defaults: {
						anchor: '100%',
                    	bodyPadding:0,
                        layout: {
                            type: 'hbox'
                        },
                        fieldDefaults:{
							labelWidth:55
				    	}
                    },
                    items:[
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	          {
    	          		    	    	xtype: 'triggerfield',
    	        		    	    	emptyText:'请输入商品编码或名称',
    	        		    	    	//width:140,
    	        		    	    	trigger1Cls:Ext.baseCSSPrefix + 'form-search-trigger',
    	        		    	    	onTriggerClick:function(e){e.keyCode=e.ENTER;this.fireEvent('specialkey',this,e);},
    	        		            	name: 'productCode',
     	        		            	fieldLabel: '商品编码',
     	        		            	tabIndex:1,
    	        		            	labelStyle:'text-align:right',
    	        		            	allowBlank:false
    	                	          },
    	                	          {
    	          		            	xtype: 'textfield',
    	        		            	readOnly:true,
    	        		            	width:250,
    	        		            	//maxWidth:200,
										//maxHeight:20,
    	        		            	name: 'productName',
    	        		            	//fieldStyle:'text-align:center',
    	        		            	labelStyle:'text-align:right',
    	        		            	fieldLabel: '商品名称',
    	        		            	allowBlank:false
    	                	          },
					                  {
											xtype: 'hiddenfield',
					                        name : 'productId'
					                  },
					                  {
											xtype: 'hiddenfield',
					                        name : 'taxRate'
					                  },
					                  {
											xtype: 'hiddenfield',
					                        name : 'batchMgr'
					                  },
    	                	          { 
    	                	        	xtype:'textfield',
    	          		        		fieldLabel: '规格',
    	          		        		readOnly:true,
    	          		        		//width:150,
    	          		        		//maxWidth:100,
										//maxHeight:20,
    	          		        		//fieldStyle:'text-align:center',
    	                                labelStyle:'text-align:right',
    	                                name:'packSpec',
    	        		        		allowBlank:true
    	                	          },
    	                	          {
											xtype:'textfield',
											fieldLabel:'生产企业',
											readOnly:true,
											//width:200,
											//maxWidth:150,
											//maxHeight:20,
											//shrinkWrap:true,
											labelStyle:'text-align:right',
											name:'manuf',
											allowBlank:true
    	                	          }
    	                	   ]
    	                   },
    	                   {
    	                   		xtype:'fieldcontainer',
    	                	    items:[
    	                	    	{
    	                	    		xtype:'combobox',
      	          		        		fieldLabel: '存货地址',
      	        		        		name:'invAddId',
      	        		        		store:invstore,
      	        		        		queryMode:'local',
    	                                labelStyle:'text-align:right',
    	                                allowBlank:false,
    	                                displayField:'inventoryAddName',
    	                                valueField:'id',
    	        						forceSelection:true,
    	        						//typeAhead : true,
    	        						listeners: {
			                        		specialkey: function(field, e){
			                        			if(field.up('form').down('hiddenfield[name=batchMgr]').getValue()=='false'){
		                        					field.up('form').down('numberfield[name=quantity]').focus(true,100);
		                        				}else{
						                        	field.up('form').down('triggerfield[name=batchNo]').focus(true,100);
		                        				}
			                        		}
			                        	}
    	                	    	},
	    	                	    {
			                        xtype: 'form',
			                		border: false,
									bodyPadding:0,
									defaults: {
				                    	bodyPadding:0,
				                        layout: {
				                            type: 'hbox'
				                        },
				                        fieldDefaults:{
											labelWidth:55
								    	}
				                    },
				                    items:[{
				                      xtype:'fieldcontainer',
				                      items:[
				                      {
											name : 'batchNo',
											fieldLabel: '批号',
											emptyText:'请按回车或点击按钮选择批号',
											//allowBlank:false,
											labelWidth:55,
											width:250,
											labelStyle:'text-align:right',
											//blankText:'批号不能为空',
											xtype: 'triggerfield',
											trigger1Cls:Ext.baseCSSPrefix + "form-search-trigger",
											onTriggerClick:function(e){
												e.keyCode=e.ENTER;//设置为Enter事件
												this.fireEvent('specialkey',this,e);//点客户查询图标执行搜索
											}
					                  },
					                  {
											xtype: 'hiddenfield',
					                        name : 'id',
					                        fieldLabel: '批号内码'
					                  },
	  	                	          {
	  	                	        	  	xtype:'textfield',
	  	                	        	 	name:'manufDate',
	  	                	        	 	//width:135,
	  	                	        	 	labelStyle:'text-align:right',
	  	                	        	  	fieldLabel:'生产日期',
	  	                	        	  	//allowBlank:false,
	  	                	        	  	format:'Y-m-d'
	  	                	          },
	  	                	          {
	  	                	        	  	xtype:'textfield',
	  	                	        	 	name:'expDate',
	  	                	        	 	//width:130,
	  	                	        	 	labelStyle:'text-align:right',
	  	                	        	  	fieldLabel:'有效期',
	  	                	        	  	//allowBlank:false,
	  	                	        	  	format:'Y-m-d'
	  	                	          }
				                   ]}]
	    	                	   }
    	                   		]
		                   },
    	                   {
    	                	   xtype:'fieldcontainer',
    	                	   items:[
    	                	   		  {
				                      		xtype: 'numberfield',
				                        	fieldLabel: '数量',
				                        	name:'quantity',
				                        	width:155,
				                        	hideTrigger :true,
				                        	tabIndex:2,
				                        	fieldStyle:'text-align:right',
				                        	labelStyle:'text-align:right',
				                        	allowBlank: false,
				                        	value:1,
				                        	enableKeyEvents:true,
				                        	listeners: {
				                        		specialkey: function(field, e){
				                        			if (e.getKey() == e.ENTER) {
								                        field.up('form').down('numberfield[name=price]').focus(true,100);
				                        			}
				                        		}
				                        	}
				                      },
				                      {
				                      		xtype: 'displayfield',
	    	        		            	readOnly:true,
	    	        		            	width:30,
	    	        		            	//labelWidth:30,
	    	        		            	name: 'unit',
	    	        		            	fieldStyle:'text-align:center'
	    	        		            	//fieldLabel: '单位',
	    	        		            	//allowBlank:false
				                      },
				                      {
				                       	    fieldLabel: '单价',
				                       	 	width:140,
				                       	 	name:'price',
				                       	 	tabIndex:3,
				                      	 	xtype: 'numberfield',
				                      	  	labelStyle:'text-align:right',
				                        	allowBlank: false,
				                        	hideTrigger :true,
				                        	minValue:0,
				                        	enableKeyEvents:true,
				                        	listeners: {
				                        		specialkey: function(field, e){
				                        			if (e.getKey() == e.ENTER) {
				                        				var btn=field.up('form').down('button');
								                        btn.fireEvent('click',btn);
								                        field.up('form').down('triggerfield').focus(true,100);
				                        			}
				                        		}
				                        	}
				                      },
				                      {xtype: 'button',text:'添加',tabIndex:4,margin:'0 0 0 10',action:'addprod',iconCls:'bill-add-button'},
				                      {xtype: 'button',text:'重置',tabIndex:4,margin:'0 0 0 10',action:'reset',iconCls:'bill-delete-button'}
    	                	   ]
    	                   }
    	            ]
    	            }]
    		    },
    		    {
    		    	xtype:'grid',
    				title:'单据明细',
    				header:false,
    				name:'otheroutbilldetails',
    				region:'center',
    				margin : '0 0 0 0',
    				anchor:'100% 55%',
    			    features: [{
    			        ftype: 'summary'
    			    }],
    				columns:[
    					{
						    xtype: 'actioncolumn',
						    width: 30,
						    sortable: false,
						    menuDisabled: true,
						    items: [{
						        iconCls: 'button-clear-filter',
						        tooltip: '删除',
						        scope: this,
						        handler: this.onRemoveClick
						    }]
						 },
						 {header:'商品编号',width:60,renderer:function(value,metaData,record){
						 		if(!Ext.isEmpty(record.product)){
						 			return record.product.get('productCode');
						 		}
						 		if(Ext.isEmpty(record.raw.product))
            						return '';
								return record.getproduct().get('productCode');
							},
							summaryType:'count',
							summaryRenderer: function(value, summaryData, dataIndex) {
								return '<b>' + Ext.String.format('合计[{0}]:', value) + '</b>'; 
							}
						 },
				         {header:'商品名称',width:120,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.product)){
						 		return record.product.get('productName');
						 	}
				         	if(Ext.isEmpty(record.raw.product))
            						return '';
				         	return record.getproduct().get('productName')
				         }},
				         {header:'规格',width:80,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.product)){
						 		return record.product.get('packSpec');
						 	}
				         	if(Ext.isEmpty(record.raw.product))
            						return '';
				         	return record.getproduct().get('packSpec');
				         }},
				         {header:'生产企业',width:100,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.product)){
						 		return record.product.get('manuf');
						 	}
				         	if(Ext.isEmpty(record.raw.product))
            						return '';
				         	return record.getproduct().get('manuf');
				         }},
				         {header:'单位',width:50,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.product)){
						 		return record.product.get('unit');
						 	}
				         	if(Ext.isEmpty(record.raw.product))
            						return '';
				         	return record.getproduct().get('unit');
				         }},
				         {
				        	 header:'数量',dataIndex:'quantity',align:'right',
				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
				             editor: {
				                    xtype: 'numberfield',
				                    allowBlank: false,
				                    hideTrigger :true,
	                	        	fieldStyle:'text-align:right',
	                	        	allowDecimals: true
				             }
				         },
				         {
				        	 header:'单价',dataIndex:'price',align:'right',
				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
				             editor: {
				                    xtype: 'numberfield',
				                    allowBlank: false,
				                    hideTrigger :true,
	                	        	fieldStyle:'text-align:right',
	                	        	allowDecimals: true
				             }
				         },
				         {
				        	 header:'税率',dataIndex:'taxRate',align:'right',
				        	 width:50,
				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
				             editor: {
				                    xtype: 'numberfield',
				                    allowBlank: false,
				                    hideTrigger :true,
	                	        	fieldStyle:'text-align:right',
	                	        	minValue:0,
	                	        	maxValue:1,
	                	        	allowDecimals: true
				             }
				         },
				         {
				        	 header:'金额',dataIndex:'amount',align:'right',
				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
				        	 summaryType:'sum',
							 summaryRenderer: function(value, summaryData, dataIndex) {
								return '<b>' + Ext.String.format('合计[{0}]:', value) + '</b>'; 
							 }
				         },
				         {header:'批号',width:80,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.batchNo)){
				         		return record.batchNo.get('batchNo');
				         	}
				         	if(Ext.isEmpty(record.raw.batchNo))
            						return '';
				         	return record.getbatchNo().get('batchNo');
				         }},
				         {header:'生产日期',width:80,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.batchNo)){
				         		return record.batchNo.get('manufDate');
				         	}
				         	if(Ext.isEmpty(record.raw.batchNo))
            						return '';
				         	return record.getbatchNo().get('manufDate');
				         }},
				         {header:'有效期',width:80,renderer:function(value,metaData,record){
				         	if(!Ext.isEmpty(record.batchNo)){
				         		return record.batchNo.get('expDate');
				         	}
				         	if(Ext.isEmpty(record.raw.batchNo))
            						return '';
				         	return record.getbatchNo().get('expDate');
				         }},
				         {
				        	 header:'结算价',dataIndex:'settlePrice',align:'right',
				        	 renderer : Ext.util.Format.numberRenderer('0.00'),
				             editor: {
				                    xtype: 'numberfield',
				                    allowBlank: false,
				                    hideTrigger :true,
	                	        	fieldStyle:'text-align:right',
	                	        	allowDecimals: true
				             }
				         }  
    				],
    				plugins: [
				         cellEditing
			        ]
    		    }
    		    
    	      		
		];
    	this.tbar=[
    	      	{xtype:'button',text:'保存',action:'saveBill',iconCls:'button-save',handler:this.onSaveBill},
    			{xtype:'button',text:'归档',action:'archiveBill',iconCls:'bill-archive-button',handler:this.onArchiveBill},
    			{xtype:'button',text:'反归档',action:'unArchiveBill',iconCls:'bill-unarchive-button',handler:this.onUnArchiveBill},
    			{xtype:'button',text:'打印',action:'printBill',iconCls:'bill-printer-button'}],
		this.callParent(arguments);
		if(!this.bill) {
			var store = Ext.create('Ext.data.Store',{
				model: 'TS.model.inv.OtherOutBillModel',
				proxy:{
					url:'otherout/createBill.do',
					type:'ajax',
					reader:{
						type:'json',
						root:''
					}
				},
				autoLoad:false
			});
			store.load({
				callback:function(records, operation, success) {
					this.bill = records[0];
					this.down('form').loadRecord(this.bill);
					this.initBill(this.bill);
				},
				scope:this
			});
		} else {
			this.down('form').loadRecord(this.bill);
			this.initBill(this.bill);
		}
	},
    onRemoveClick: function(gridView, rowIndex){
    	 if(this.bill && this.bill.get('archived')) {
			Ext.Msg.show({
					title:'ThinkGsp',
					msg:'单据已经归档,不能删除!',
					buttons:Ext.Msg.OK,
					icon:Ext.Msg.WARNING
			});
			return;
		 };
    	 Ext.Msg.confirm('ThinkGSP','真的要删除选择的商品吗?',function(b){
			if(b=='yes'){
				gridView.getStore().removeAt(rowIndex);
	 			gridView.refresh();
			}
		});
    },
     //
    initBill: function(model) {
    	var deptField = this.down('combobox[name=deptName]');
    	deptField.setValue(model.getdept().get('deptName'));
    	var empField = this.down('combobox[name=empId]');
    	empField.select(model.getemp().get('empId'));
    	var makerField = this.down('textfield[name=makerName]');
    	makerField.setValue(model.getmaker().get('empName'));
    	if(model.customerHasOneInstance != null) {
    		this.down('triggerfield').setValue(model.getcustomer().get('customerCode'));
    		this.down('textfield[name=customerName]').setValue(model.getcustomer().get('customerName'));
    	}
    	var billTypeField = this.down('combobox[name=billType]');
    	billTypeField.setValue(model.get('billType'));
    	this.down('grid').reconfigure(model.details());
    	this.onUpdateState(this,model);
     },
     onUpdateState:function(form,bill) {
    	 if(bill.get('archived')) {
    		 form.down('button[action=archiveBill]').setDisabled(true);
    		 form.down('button[action=saveBill]').setDisabled(true);
    		 form.down('button[action=unArchiveBill]').setDisabled(false);
    	 } else {
    		 form.down('button[action=saveBill]').setDisabled(false);
    		 form.down('button[action=archiveBill]').setDisabled(false);
    		 form.down('button[action=unArchiveBill]').setDisabled(true);
    	 }
    	 if(bill.get('billId') == 0) {
    		 this.setTitle('其它出库单-新增');
    		 form.down('triggerfield[name=customerCode]').focus(true,100);
    	 } else if(this.bill.get('archived')) {
			 this.setTitle('其它出库单-查看');
		 } else {
			 this.setTitle('其它出库单-编辑');
			 form.down('triggerfield[name=productCode]').focus(true,100);
		 }
     }
});